<template>
  <div class="app-container">
    <el-form :inline="true" @submit.native.prevent>
      <el-form-item>
        <el-input v-model="listContext.filter" :placeholder="$t('AbpIdentity[\'Search\']')" @keyup.enter.native="fetchData" />
      </el-form-item>
      <el-form-item>
        <el-select v-model="listContext.roleIds" clearable multiple filterable :placeholder="$t('AbpIdentity[\'RoleName\']')">
          <el-option
            v-for="item in assignableRoles"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <div class="block">
          <el-cascader
            v-model="listContext.organizationUnitIds"
            :options="assignableOrganizationUnitsTree"
            :props="{ multiple: true, checkStrictly: true, emitPath: false, expandTrigger: 'hover', label: 'displayName', value: 'id' }"
            clearable
            filterable
            :show-all-levels="false"
            :placeholder="$t('BookStore2[\'OrganizationUnit\']')"
          >
            <template slot-scope="{ node, data }">
              <span>{{ data.displayName }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData">
          <i class="el-icon-search" />
        </el-button>
      </el-form-item>
      <el-button
        v-if="checkPermission('AbpIdentity.Users.Create')"
        type="primary"
        style="float: right"
        @click="openCreateUserDialog"
      >
        <i class="el-icon-plus" />{{ $t('AbpIdentity["NewUser"]') }}
      </el-button>
    </el-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      :element-loading-text="$t('AbpIdentity[\'LoadingWithThreeDot\']')"
      :empty-text="$t('AbpIdentity[\'NoDataAvailableInDatatable\']')"
      border
      fit
      highlight-current-row
      height="calc(100vh - 225px)"
      @sort-change="sortChange"
    >
      <el-table-column :label="$t('BookStore2[\'DisplayName:PortraitImg\']')" prop="extraProperties.PortraitBlob_BlobName" width="80">
        <template slot-scope="scope">
          <img v-if="scope.row.extraProperties.PortraitBlob_BlobName" :src="getFilePathByName(scope.row.extraProperties.PortraitBlob_BlobName)" style=" width: 30px;height: 30px;display: block;" alt="">
        </template>
      </el-table-column>
      <el-table-column :label="$t('BookStore2[\'DisplayName:UserName\']')" prop="userName" sortable="custom">
        <template slot-scope="scope">
          <i v-show="isLockedOutAsync(scope.row.lockoutEnabled, scope.row.lockoutEnd)" class="el-icon-lock" />
          {{ scope.row.userName }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('AbpIdentity[\'DisplayName:Name\']')" prop="name" sortable="custom">
        <template slot-scope="scope">
          {{ (scope.row.name || '') + ' ' + (scope.row.surname || '') }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('AbpIdentity[\'RoleName\']')" prop="roleNames">
        <template slot-scope="scope">
          {{ scope.row.roles.map(r => r.name).join(',') }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('BookStore2[\'OrganizationUnit\']')" prop="organizationUnitNames" width="120px">
        <template slot-scope="scope">
          {{ scope.row.organizationUnits.map(r => r.displayName).join(',') }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('AbpIdentity[\'DisplayName:Email\']')" prop="email" sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.email }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('AbpIdentity[\'DisplayName:PhoneNumber\']')" prop="phoneNumber" width="120px">
        <template slot-scope="scope">
          {{ scope.row.phoneNumber }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('BookStore2[\'DisplayName:Address\']')" prop="extraProperties.Address">
        <template slot-scope="scope">
          {{ scope.row.extraProperties.Address }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('BookStore2[\'DisplayName:SocialSecurityCard\']')" prop="extraProperties.SocialSecurityCard">
        <template slot-scope="scope">
          <el-button v-if="scope.row.extraProperties.SocialSecurityCardBlob_BlobName" type="text" @click="clickActionDropDown({ action: 'viewSocialSecurityCard', user: scope.row })">{{ scope.row.extraProperties.SocialSecurityCard }}</el-button>
          <span v-else>{{ scope.row.extraProperties.SocialSecurityCard }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('BookStore2[\'DisplayName:Credits\']')" prop="extraProperties.Credits">
        <template slot-scope="scope">
          {{ scope.row.extraProperties.Credits }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('BookStore2[\'Parcels\']')" prop="extraProperties.Parcels">
        <template slot-scope="scope">
          {{ scope.row.extraProperties.Parcels }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('BookStore2[\'DisplayName:EntryDate\']')" prop="extraProperties.EntryDate">
        <template slot-scope="scope">
          {{ scope.row.extraProperties.EntryDate | dateYMDFormat }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('BookStore2[\'DisplayName:LeaveDate\']')" prop="extraProperties.LeaveDate">
        <template slot-scope="scope">
          {{ scope.row.extraProperties.LeaveDate | dateYMDFormat }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('AbpIdentity[\'Actions\']')">
        <template slot-scope="scope">
          <el-dropdown trigger="click" @command="clickActionDropDown">
            <el-button type="primary">
              <i class="el-icon-setting" />
              {{ $t('AbpIdentity[\'Actions\']') }}
              <i class="el-icon-arrow-down" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="checkPermission('AbpIdentity.Users.Update')" :command="{ action: 'edit', user: scope.row }">{{ $t('AbpIdentity[\'Edit\']') }}</el-dropdown-item>
              <!--              <el-dropdown-item :command="{ action: 'claims', user: scope.row }">{{ $t('AbpIdentity[\'Claims\']') }}</el-dropdown-item>-->
              <el-dropdown-item v-if="!isLockedOutAsync(scope.row.lockoutEnabled, scope.row.lockoutEnd)" :command="{ action: 'lock', user: scope.row }">{{ $t('AbpIdentity[\'Lock\']') }}</el-dropdown-item>
              <el-dropdown-item v-else :command="{ action: 'unlock', user: scope.row }">{{ $t('AbpIdentity[\'Unlock\']') }}</el-dropdown-item>
              <el-dropdown-item v-if="checkPermission('AbpIdentity.Users.ManagePermissions')" :command="{ action: 'permission', user: scope.row }">{{ $t('AbpIdentity[\'Permissions\']') }}</el-dropdown-item>
              <el-dropdown-item v-if="checkPermission('AbpIdentity.Users.ChangePassword')" :command="{ action: 'setPassword', user: scope.row }">{{ $t('AbpIdentity[\'SetPassword\']') }}</el-dropdown-item>
              <!--              <el-dropdown-item :command="{ action: 'twoFactor', user: scope.row }">{{ $t('AbpIdentity[\'TwoFactor\']') }}</el-dropdown-item>-->
              <el-dropdown-item v-if="checkPermission('AbpIdentity.Users.Delete')" :command="{ action: 'delete', user: scope.row }">{{ $t('AbpIdentity[\'Delete\']') }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="margin-top: 10px">
      <el-pagination
        :page-sizes="pageContext.pageSizes"
        :page-size.sync="listContext.maxResultCount"
        :current-page.sync="pageContext.currentPage"
        :total="pageContext.totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchData"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :title="dialogSocialSecurityCardTitle" :visible.sync="dialogSocialSecurityCardVisible" width="30%" append-to-body>
      <img width="100%" :src="dialogSocialSecurityCardUrl" alt="">
    </el-dialog>
    <create-or-edit-user
      ref="createOrEditUser"
      :visible.sync="userDialogVisible"
      :context="userDialogCtx"
      :assignable-roles="assignableRoles"
      :assignable-organization-units-tree="assignableOrganizationUnitsTree"
      @saveSucceed="fetchData"
    />
    <lock-user ref="lockUser" :visible.sync="lockUserDialogVisible" :context="lockUserDialogCtx" @succeed="succeed_lockUser" />
    <user-or-role-permission ref="userOrRolePermission" :visible.sync="permissionDialogVisible" :context="permissionDialogCtx" />
    <set-password ref="setPassword" :visible.sync="setPasswordDialogVisible" :context="setPasswordDialogCtx" />
  </div>
</template>

<script>
import {
  deleteById,
  getList,
  unlockUser,
  getAssignableRoles,
  getAssignableOrganizationUnits
} from '@/api/administration/user/user'
import { convertTree } from '@/utils/treeUtil'
import CreateOrEditUser from '@/views/administration/identity/user/components/createOrEditUser'
import LockUser from '@/views/administration/identity/user/components/lockUser'
import UserOrRolePermission from '@/views/administration/identity/components/userOrRolePermission'
import moment from 'moment'
import SetPassword from '@/views/administration/identity/user/components/setPassword'
import { checkPermission, getFilePathByName } from '@/utils/abp'

export default {
  name: 'User',
  components: { SetPassword, UserOrRolePermission, CreateOrEditUser, LockUser },
  data() {
    return {
      list: null,
      listLoading: false,
      pageContext: {
        pageSizes: [10, 25, 50, 100],
        totalCount: 0,
        currentPage: 1
      },
      listContext: {
        filter: '',
        roleIds: [],
        organizationUnitIds: [],
        sorting: '',
        skipCount: 0,
        maxResultCount: 10
      },
      userDialogVisible: false,
      userDialogCtx: {
        title: '',
        actionMode: '',
        id: ''
      },
      permissionDialogVisible: false,
      permissionDialogCtx: {
        providerName: '',
        providerKey: ''
      },
      lockUserDialogVisible: false,
      lockUserDialogCtx: {
        user: null
      },
      setPasswordDialogVisible: false,
      setPasswordDialogCtx: {
        user: null
      },
      dialogSocialSecurityCardVisible: false,
      dialogSocialSecurityCardTitle: '',
      dialogSocialSecurityCardUrl: '',
      assignableRoles: [],
      assignableOrganizationUnitsTree: []
    }
  },
  async created() {
    const promiseResult = await Promise.all([
      getAssignableOrganizationUnits(),
      getAssignableRoles()
    ])
    if (promiseResult[0].items) {
      this.assignableOrganizationUnitsTree = convertTree(promiseResult[0].items)
    }
    console.log(this.assignableOrganizationUnitsTree)
    this.assignableRoles = promiseResult[1].items

    this.fetchData()
  },
  methods: {
    checkPermission,
    getFilePathByName,
    fetchData() {
      this.listLoading = true

      getList(this.listContext).then((response) => {
        this.list = response.items
        this.pageContext.totalCount = response.totalCount
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleCurrentChange(currentPage) {
      this.listContext.skipCount = (currentPage - 1) * this.listContext.maxResultCount
      this.fetchData()
    },
    sortChange({ prop, order }) {
      this.listContext.sorting = ''
      if (order) {
        this.listContext.sorting = prop + ' ' + order
      }
      this.fetchData()
    },
    clickActionDropDown(ctx) {
      switch (ctx.action) {
        case 'edit':
          this.openEditUserDialog(ctx.user.id)
          break
        case 'lock':
          this.openLockUserDialog(ctx.user)
          break
        case 'unlock':
          unlockUser(ctx.user.id).then(resp => {
            ctx.user.lockoutEnd = moment().add(-1, 's').format()
          })
          break
        case 'permission':
          this.openPermissionDialog(ctx.user)
          break
        case 'setPassword':
          this.openSetPasswordDialog(ctx.user)
          break
        case 'delete':
          this.$confirm(this.$t('AbpIdentity[\'AreYouSure\']')).then(async _ => {
            await deleteById(ctx.user.id)
            this.$message({
              message: this.$t('AbpIdentity[\'Ok\']'),
              type: 'success'
            })
            this.fetchData()
          }).catch(_ => {})
          break
        case 'viewSocialSecurityCard':
          this.dialogSocialSecurityCardTitle = ctx.user.extraProperties.SocialSecurityCardBlob_FileName
          this.dialogSocialSecurityCardUrl = getFilePathByName(ctx.user.extraProperties.SocialSecurityCardBlob_BlobName)
          this.dialogSocialSecurityCardVisible = true
          break
      }
    },
    openCreateUserDialog() {
      this.userDialogVisible = true
      this.userDialogCtx = {
        title: this.$t('AbpIdentity[\'NewUser\']'),
        actionMode: 'create'
      }
    },
    openEditUserDialog(id) {
      this.userDialogVisible = true
      this.userDialogCtx = {
        title: this.$t('AbpIdentity[\'Edit\']'),
        actionMode: 'edit',
        id: id
      }
    },
    openLockUserDialog(user) {
      this.lockUserDialogVisible = true
      this.lockUserDialogCtx = {
        user: user
      }
    },
    openSetPasswordDialog(user) {
      this.setPasswordDialogVisible = true
      this.setPasswordDialogCtx = {
        user: user
      }
    },
    openPermissionDialog(user) {
      this.permissionDialogVisible = true
      this.permissionDialogCtx = {
        providerName: 'U',
        providerKey: user.id
      }
    },
    succeed_lockUser(user, seconds) {
      user.lockoutEnd = moment().add(seconds, 's').format()
    },
    isLockedOutAsync(lockoutEnabled, lockoutEnd) {
      if (!lockoutEnabled) {
        return false
      }
      return moment().isBefore(moment(lockoutEnd))
    }
  }
}
</script>

<style lang="scss" scoped>
</style>

